<?php
require_once( PHP_PATH . 'common.php' );

$template->welcomeMsg = "Your All Expenses";

$errorMsg = "";
$isExport = isset( Url::$pageVars[ 'GETPOST' ][ 'export' ] ) ? true : false;
$quantity = $isExport ? 500 : 20;

$yearMonth = date( 'Ym' );
$teamId = isset( Url::$pageVars[ 'GETPOST' ][ 'tid' ] ) ? Url::$pageVars[ 'GETPOST' ][ 'tid' ] : 0;
$template->teams = $teams = Utility::getUserTeams( $teamId );
$template->teamClass = '';
if( count( $teams ) == 1 ){
	$teamId = $teams[0][ 'id' ];
	$template->teamClass = "hide";
}elseif( count( $teams ) > 1 && !isset( Url::$pageVars[ 'GETPOST' ][ 'tid' ] ) ){
	$teamId = $teams[0][ 'id' ];
}

$template->viewLink = $teamId > 0 ? "/team-report/nv/tid/$teamId/" : '/team-report/';

$paging = array();
$expenses = array();
if( $teamId > 0 ){
	// remove expense entry from table
	if( isset( Url::$pageVars[ 'GETPOST' ][ 'removeExpense' ] ) ){
		try{
			ExpenseUtility::removeExpenseData( Url::$pageVars[ 'GETPOST' ][ 'removeExpense' ] );
			header( 'Location: /expenses/' );
			exit;
		}catch( Exception $ex ){
			$errorMsg = $ex->getMessage();
		}
	}


	$PageNo = isset( Url::$pageVars['GETPOST']['page'] ) ? Url::$pageVars['GETPOST']['page'] : 1;
	$teamExpenses = ExpenseUtility::getExpenses( $teamId, '', $PageNo, $quantity );
	if( count( $teamExpenses ) > 0 ){
		$expenses = $teamExpenses[ 'expenses' ];
		$paging = $teamExpenses[ 'paging' ];
	}
}
$template->expenses = $expenses;
$template->paging = $paging;
$template->errorMsg = $errorMsg;
// export the record
if( $isExport ){
	$exports = array();
	foreach( $expenses as $expense ){
		$expense[ 'desc' ] = str_replace( ',', '-', $expense[ 'desc' ] );
		$expense[ 'group' ] = str_replace( ',', '-', $expense[ 'group' ] );
		$expense[ 'team' ] = str_replace( ',', '-', $expense[ 'team' ] );
		$expense[ 'team' ] = str_replace( ',', '-', $expense[ 'team' ] );
		$expense[ 'date' ] = str_replace( ',', '-', $expense[ 'date' ] );
		$expense[ 'creator' ] = str_replace( ',', '-', $expense[ 'creator' ] );

		unset( $expense[ 'shortDesc' ] );
		unset( $expense[ 'id' ] );
		unset( $expense[ 'canDelete' ] );

		$exports[] = $expense;
	}

	$fileName = 'expenses-' . date( 'd-M-Y-H-i-s' );
	header( "Content-type: application/vnd.ms-excel");
	header( "Content-Disposition: attachment;Filename=$fileName.csv");
	echo exportAsCsv( $exports );
	exit;
}


